package gateway.server.lifecycle;

import gateway.api.aware.HttpClientAware;
import gateway.api.engine.Engine;

import java.net.http.HttpClient;
import java.time.Duration;

/**
 * @author Jin Zheng
 * @since 1.0 2020-09-27
 */
public class HttpClientLifecycle implements Lifecycle
{
	private final HttpClient httpClient;

	public HttpClientLifecycle(Engine engine)
	{
		this.httpClient = HttpClient.newBuilder()
				.version(HttpClient.Version.HTTP_1_1)
				.executor(engine.getExecutorService())
				.connectTimeout(Duration.ofMinutes(1))
				.build();
	}

	@Override
	public boolean accepted(Object target)
	{
		return target instanceof HttpClientAware;
	}

	@Override
	public void handle(Object target) throws Exception
	{
		HttpClientAware aware = (HttpClientAware) target;
		aware.setHttpClient(httpClient);
	}
}
